package it.struts.helloworld.action;


import it.struts.helloworld.form.AddToCartForm;
import it.struts.helloworld.model.Carrello;
import it.struts.helloworld.model.Prodotti;
import it.struts.helloworld.services.CarrelloService;
import it.struts.helloworld.services.ProdottiService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


/**
 * Action class to add items to the cart.
 */

public class AddToCartAction extends Action {

	/**
	 * Execute method.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance
	 * @param form
	 *            The optional ActionForm bean for this request
	 * @param request
	 *            The servlet request we are processing
	 * @param response
	 *            The servlet response we are creating
	 * 
	 * @exception Exception
	 *                if business logic throws an exception
	 */

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		AddToCartForm objForm = (AddToCartForm) form;

//		Utilities utill = new Utilities();

		// Retrieve the DAO Reference
//		roseindia.dao.ShoppingCartDAO shoppingCartDAO = (roseindia.dao.ShoppingCartDAO) ServiceFinder
//				.getContext(request).getBean(ShoppingCartConstants.DAO_BEAN);
		// By Default show the Add/Edit Page
		String forwardToPage = "input";
		String strError = "";

		// getting curency symbol
//		String CurrencySymbol = shoppingCartDAO.getCurrencySymbol();
//		request.setAttribute("csymbol", CurrencySymbol);

		HttpSession session = request.getSession(true);

		Carrello cart;

		if (session.getAttribute("cart") == null) {
			cart = new Carrello();
			session.setAttribute("cart", cart);
		} else {
			cart = (Carrello) session.getAttribute("cart");

		}

		try {

			// In case of delete, Delete item from shopping cart
			if (request.getParameter("action").equals("delete")) {
				System.out.println("DELETE");
				int productid = Integer.parseInt(request.getParameter("pid"));
				// Delete Item from cart
				cart.removeItem(productid);

				// Set to the request attribute to show the items in the cart
				request.setAttribute("cartitems", cart.getItems());

				request.setAttribute("action", "Edit");
			}

			// In case of Edit retrieve the data from datbase and set the values
			// in the form obj
			if (request.getParameter("action").equals("Edit")) {

				if (request.getParameter("totalitems") != null) {

					int totalitms = Integer.parseInt(request
							.getParameter("totalitems"));

					for (int i = 1; i < totalitms; i++) {

						Prodotti item = new Prodotti();

						// Set values
						item.setProd_id(Integer.parseInt(request
								.getParameter("itemcode" + i)));

						// find per item cast by product id

						double perItemCast = CarrelloService
								.getPrezzoPerProdotto(Integer.parseInt(request
										.getParameter("itemcode" + i)));

						// rounding item cost up to 2 decimal places
//						double itemsCast = Integer.parseInt(request
//								.getParameter("quantity" + i))
//								* perItemCast;
//
//						double roundedItemCost = utill
//								.RoundDoubleTo2DecimalPlaces(itemsCast, 2);
//
						item.setPrezzo(perItemCast);

						// Set Item quantity
						item.setQuantita(Integer.parseInt(request
								.getParameter("quantity" + i)));
						// Update to cart

						cart.addItem(item);

					}
				} else {

					Prodotti pojoObj = ProdottiService.loadProductToCart(Integer.parseInt(request.getParameter("productid")));

					Prodotti item = new Prodotti();

					item.setProd_id((pojoObj.getProd_id()));
					item.setNome((pojoObj.getNome()));
					item.setPrezzo((pojoObj.getPrezzo()));
					item.setQuantita((1));
					cart.addItem(item);
			

				}

				session.setAttribute("cart", cart);

				// Set to the request attribute to show the items in the cart
				request.setAttribute("cartitems", cart.getItems());

				// for the edit form
				forwardToPage = "input";
				// Set the action to update
				request.setAttribute("action", "Edit");
			}

		} catch (Exception e) {
			forwardToPage = "input";
			e.printStackTrace();
		}
		// Display the registration form to the user
		return mapping.findForward(forwardToPage);
	}

}
